package com.hmall.gateway.filters;

import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

@Component
@Order(0)
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter {

    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 2、 判断是否需要拦截
        if (isExcludePath(request.getPath().toString())) {
            return chain.filter(exchange);

        }
        // 3、 获取请求头中的token
        String authorization = request.getHeaders().getFirst("Authorization");

        if (StrUtil.isBlank(authorization)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 4、 校验并解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(authorization);
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 5、 如果有传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange ex = exchange.mutate().request(builder -> builder.header("user-info", userInfo)).build();
        return chain.filter(ex);
    }

    private boolean isExcludePath(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        return excludePaths.stream().anyMatch(excludePath -> pathMatcher.match(excludePath, path));
    }
}
